package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {

    @Autowired
    private Configuration configuration;


    @Autowired
    @Qualifier("minIOFileStorageService")
    private FileStorageService fileStorageService;

    @Value("${file.minio.prefix}")
    private String prefix;

    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    AuthorMapper authorMapper;




    /**
     * 生成静态页面
     * @param content
     * @param apArticle
     */
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        //获取模板信息
        try {
            //创建模板对象
            Template template = configuration.getTemplate("article.ftl");
            //填充数据
            Map<String , Object> map = new HashMap<>();
            //文章正文内容
            map.put("content" , JSON.parseArray(content));
            //文章对象
            map.put("article" , apArticle);
            //获取作者信息
            ApAuthor author = authorMapper.selectById(apArticle.getAuthorId());
            map.put("authorApUserId" , author.getUserId());

            //创建一个字符串输出流
            StringWriter stringWriter = new StringWriter();
            //将数据输出到模板上
            template.process(map,stringWriter);

            InputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes(StandardCharsets.UTF_8));

            //生成静态页面 将html文件上传到minio中
            //                  minio桶前缀          静态页面名字                             格式           输出流
            String path = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", inputStream);

            //修改ap_article表 保存static_url字段
            apArticle.setStaticUrl(path);
            apArticleMapper.updateById(apArticle);

            //打印日志
            log.info("文章详情静态页生成成功 staticUrl=====> {}", path);

        } catch (IOException e) {
            e.printStackTrace();
            log.error("文章详情静态页生成失败=====>articleId : {}    ========> {}", apArticle.getId(), e.getCause());

        } catch (TemplateException e) {
            e.printStackTrace();
            log.error("文章详情静态页生成失败=====>articleId : {}    ========> {}", apArticle.getId(), e.getCause());

        }
    }
}
